import router from '@/router';
import { defineStore } from 'pinia'
import { Ref, ref, nextTick } from "vue";
export const useStore = defineStore('tags', () => {
  const tags: Ref<any[]> = ref([]);
  const tag: Ref<any> = ref('');
  // 获取唯一key
  const getKey = () => {
    return String(new Date().getTime()) + String((Math.random() * 1000).toFixed(0));
  }

  // 添加固定标签
  const addAffixTag = (e: any) => {
    if (tags.value.findIndex(x => x.name === e.name) === -1) {
      e.key = getKey();
      tags.value.unshift(e);
    }
  }

  // 添加标签
  const addTag = (e: any) => {
    if (tags.value.findIndex(x => x.name === e.name) === -1) {
      e.key = getKey();
      tags.value.push(e);
    } else {
      e.key = tags.value.find(x => x.name === e.name).key;
      tags.value.splice(tags.value.findIndex(x => x.name === e.name), 1, e);
    }
  }

  // 简单移除标签,不执行跳转动作
  const removeTagSimple = (name: any) => {
    tags.value.splice(tags.value.findIndex(x => x.name === name), 1);
  }

  // 移除标签
  const removeTag = async (name: any, next?: string) => {
    removeTagSimple(name);
    if (next) {
      tag.value = next;
    } else {
      tag.value = tags.value[tags.value.length - 1].name;
    }
    router.push({
      name: tags.value.find(x => x.name === tag.value).name,
      query: tags.value.find(x => x.name === tag.value).query,
      params: tags.value.find(x => x.name === tag.value).params,
    });
  }

  // 标签切换
  const tagChange = (name: any) => {
    tag.value = name;
  }

  // 标签对应页面刷新
  const refresh = (name: any, done: () => any) => {
    let item = tags.value.find(x => x.name === name);
    let idx = tags.value.findIndex(x => x.name === name);
    tags.value.splice(idx, 1);
    nextTick(() => {
      item.key = getKey();
      tags.value.splice(idx, 0, item);
      setTimeout(() => {
        done()
      }, 500)
    })
  }
  // 清空标签
  const tagsClear = () => {
    tags.value = [];
  }
  return {
    tags,
    tag,
    tagsClear,
    addAffixTag,
    addTag,
    removeTagSimple,
    removeTag,
    tagChange,
    refresh,
  }
}, {
  persist: {
    enabled: true,
    strategies: [{
      key: process.env.VUE_APP_ENV + "tags",
      storage: sessionStorage,
    }]
  }
} as any)
